package com.hanhai.material.device.controller;

import com.alibaba.fastjson.JSONObject;
import com.hanhai.material.common.result.KingdeeResult;
import com.hanhai.material.common.result.Result;
import com.hanhai.material.common.result.ResultTool;
import com.hanhai.material.device.entity.SysDocument;
import com.hanhai.material.device.entity.SysWorkPlan;
import com.hanhai.material.device.model.miscellaneousdelivery.MiscellaneousDelivery;
import com.hanhai.material.device.model.miscellaneousdelivery.UpdateMiscellaneousDelivery;
import com.hanhai.material.device.service.SysDocumentService;
import com.hanhai.material.device.service.SysWorkPlanService;
import com.hanhai.material.device.utils.kingdee.KingdeeUtils;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.hanhai.material.device.entity.table.SysDocumentTableDef.SYS_DOCUMENT;
import static com.hanhai.material.device.entity.table.SysWorkPlanTableDef.SYS_WORK_PLAN;
import static com.hanhai.material.utils.TimeUtils.fromDateToString;
import static com.mybatisflex.core.query.QueryMethods.distinct;

/**
 * 控制层。
 *
 * @author youchuang
 * @since 2024/04/24 10:44:01
 */
@RestController
@RequestMapping("/document")
public class SysDocumentController {

    @Autowired
    private SysDocumentService sysDocumentService;

    @Autowired
    private KingdeeUtils kingdeeUtils;

    /**
     * 添加。
     *
     * @param sysDocument
     * @return {@code true} 添加成功，{@code false} 添加失败
     */
    @PostMapping("save")
    public Result<?> save(@RequestBody SysDocument sysDocument) {
        Date now = new Date();
        String dataId = fromDateToString("yyyyMMddHHmmss", sysDocument.getCollectionDate()) + sysDocument.getMaterialId() + sysDocument.getNum();
        sysDocument.setDataId(dataId);
        sysDocument.setCollectionDate(sysDocument.getCollectionDate());
        sysDocument.setCollectionDateTime(now);
        boolean result = this.sysDocumentService.save(sysDocument);

        return result ? ResultTool.success() : ResultTool.fail();
    }

    /**
     * 根据主键删除。
     *
     * @param document 主键
     * @return {@code true} 删除成功，{@code false} 删除失败
     */
    @PostMapping("remove")
    public Result<?> remove(@RequestBody SysDocument document) throws IOException {
        boolean result = this.sysDocumentService.removeById(document.getId());
        if(document.getKingNo()!=null){
            this.kingdeeUtils.deleteMaterialInfo(document.getKingNo());
        }
        return result ? ResultTool.success() : ResultTool.fail();
    }

    /**
     * 根据主键更新。
     *
     * @param sysDocument
     * @return {@code true} 更新成功，{@code false} 更新失败
     */
    @PostMapping("update")
    public Result<?> update(@RequestBody SysDocument sysDocument) throws IOException {
        boolean result = this.sysDocumentService.updateById(sysDocument);
        if(result&&sysDocument.getKingNo()!=null){

           return this.singleMake(sysDocument);

        }
        return result ? ResultTool.success() : ResultTool.fail();
    }

    /**
     * 查询所有。
     *
     * @return 所有数据
     */
    @PostMapping("list")
    public Result<?> list(@RequestBody SysDocument sysDocument) {
        QueryWrapper queryWrapper = QueryWrapper.create();
        queryWrapper.where(SYS_DOCUMENT.COLLECTION_DATE.eq(fromDateToString("yyyy-MM-dd", sysDocument.getCollectionDate())));
        queryWrapper.where(SYS_DOCUMENT.CREATE_USER_ID.eq(sysDocument.getCreateUserId()));
        queryWrapper.where(SYS_DOCUMENT.FROB.eq(sysDocument.getFrob()));
        queryWrapper.orderBy(SYS_DOCUMENT.CREATE_TIME, false);

        List<SysDocument> sysDocumentList = this.sysDocumentService.list(queryWrapper);
        return sysDocumentList.isEmpty() ? ResultTool.fail() : ResultTool.success(sysDocumentList);
    }

    /**
     * 根据主键获取详细信息。
     *
     * @param materialId 主键
     * @return 详情
     */
    @GetMapping("getInfo/{materialId}")
    public JSONObject getInfo(@PathVariable String materialId) throws IOException {
        return this.kingdeeUtils.getMaterialInfo(materialId);
    }

    /**
     * 分页查询。
     *
     * @param page 分页对象
     * @return 分页对象
     */
    @GetMapping("page")
    public Page<SysDocument> page(Page<SysDocument> page) {
        return sysDocumentService.page(page);
    }

    @PostMapping("/singleMake")
    public Result<?> singleMake(@RequestBody SysDocument document) throws IOException {
        KingdeeResult kingdeeResult = null;
        if (document.getKingNo() == null) {
            MiscellaneousDelivery miscellaneousDelivery = this.kingdeeUtils.getMiscellaneousDelivery(document);

            kingdeeResult = this.kingdeeUtils.addMaterialInfo(miscellaneousDelivery);
            return singleUpdate(kingdeeResult,document);
        } else {
            QueryWrapper queryWrapper=QueryWrapper.create();
            queryWrapper.where(SYS_DOCUMENT.KING_NO.eq(document.getKingNo()));
            queryWrapper.where(SYS_DOCUMENT.ID.ne(document.getId()));
            List<SysDocument> documentList=this.sysDocumentService.list(queryWrapper);
            documentList.add(document);
            UpdateMiscellaneousDelivery miscellaneousDelivery = this.kingdeeUtils.getUpdateMiscellaneousDeliveryList(documentList);
            kingdeeResult = this.kingdeeUtils.updateMaterialInfo(miscellaneousDelivery);
            return  batchUpdate(kingdeeResult,documentList);
        }

    }

    @PostMapping("/batchMake")
    public Result<?> batchMake(@RequestBody List<SysDocument> documentList) throws IOException {
        documentList=documentList.stream().filter(item-> StringUtils.isBlank(item.getKingNo())).collect(Collectors.toList());
        if(documentList.isEmpty()){
            return ResultTool.fail();
        }

        MiscellaneousDelivery miscellaneousDelivery = this.kingdeeUtils.getMiscellaneousDeliveryList(documentList);
        KingdeeResult kingdeeResult = this.kingdeeUtils.addMaterialInfo(miscellaneousDelivery);

        return batchUpdate(kingdeeResult,documentList);
    }

    public Result<?> singleUpdate(KingdeeResult kingdeeResult,SysDocument document){
        if (kingdeeResult != null) {
            if (kingdeeResult.getStatusCode() == 200) {
                JSONObject jsonObject = JSONObject.parseObject(kingdeeResult.getData());
                try {
                    document.setMake(true);
                    document.setKingNo(jsonObject.getString("BillNo"));
                    document.setKingId(jsonObject.getString("BillInterID"));
                } catch (Exception e) {

                }
                this.sysDocumentService.updateById(document);
                return ResultTool.success(document);
            }else {
                return ResultTool.fail();
            }

        }else {
            return ResultTool.fail();
        }
    }

    public Result<?> batchUpdate(KingdeeResult kingdeeResult,List<SysDocument> documentList){
        if (kingdeeResult != null) {
            if (kingdeeResult.getStatusCode() == 200) {
                JSONObject jsonObject = JSONObject.parseObject(kingdeeResult.getData());
                for(SysDocument document:documentList){
                    try {
                        document.setMake(true);
                        document.setKingNo(jsonObject.getString("BillNo"));
                        document.setKingId(jsonObject.getString("BillInterID"));
                    } catch (Exception e) {

                    }
                }
                this.sysDocumentService.updateBatch(documentList);
                return ResultTool.success(documentList.get(0));
            }else {
                return ResultTool.fail();
            }

        }else {
            return ResultTool.fail();
        }
    }
    @Autowired
    SysWorkPlanService sysWorkPlanService;
    @GetMapping("/getMoldInfoList/{moldNo}")
    public Result<?> getMoldInfoList(@PathVariable String moldNo){
        LocalDateTime endTime=LocalDateTime.now();
        LocalDateTime startTime=endTime.minusDays(30);
        QueryWrapper queryWrapper=QueryWrapper.create();
        queryWrapper.select(distinct(SYS_WORK_PLAN.MOLD_NO));
        queryWrapper.where(SYS_WORK_PLAN.MOLD_NO.isNotNull());
        queryWrapper.where(SYS_WORK_PLAN.PLAN_START_TIME.between(startTime,endTime));
        if(moldNo!=null&& !moldNo.equals("null")){
            queryWrapper.where(SYS_WORK_PLAN.MOLD_NO.like(moldNo));
        }
        queryWrapper.orderBy(SYS_WORK_PLAN.MOLD_NO,true);
        System.out.println("SQL:"+queryWrapper.toSQL());
        List<SysWorkPlan> sysWorkPlanList=this.sysWorkPlanService.list(queryWrapper);
        return  sysWorkPlanList.isEmpty()?ResultTool.fail():ResultTool.success(sysWorkPlanList);
    }

}
